package com.youku.mson.serializer;

import java.lang.reflect.Field;

import com.youku.mson.util.ReflectUtils;

public class ObjecSerializer implements JsonSerializer {

	@Override
	public void serialize(JsonWriter out, Object target) {
		if (target == null) {
			out.writeNull();
		} else {
			out.beginObject();
			Field[] fields = ReflectUtils.getDeclaredFields(target.getClass());

			for (Field field : fields) {
				JsonSerializer serializer = JsonSerializerFactory.getSerializer(field.getType());

				Object value = ReflectUtils.invokeGetter(target, field.getName(), new Class<?>[] {}, new Object[] {});

				out.writeString(field.getName());
				out.writeColon();
				serializer.serialize(out, value);

				out.writeComma();
			}

			if (out.endWith(",")) {
				out.deleteEnd();
			}

			out.endObject();
		}
	}
}
